import React, {useEffect, useState} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  ScrollView,
  Image,
  TextInput,
} from 'react-native';
import {List, Picker, Toast} from '@ant-design/react-native';
import XPay from 'react-native-puti-pay';
import {useNavigation} from '@react-navigation/native';
import AreaView from '../../components/Layout/AreaView';
import styles from './style';
import OrderPrdList from '../../components/OrderPrdList';
import {
  courseDetail,
  couponcustList,
  profile,
  createOrder,
  orderCalculateAmt,
  alipayAppPay,
  wxpayAppPay,
} from '../../service/home';

const PaySure = (props) => {
  const navigation = useNavigation();
  const [courseData, setCourseData] = useState({});
  const [couponData, setCouponData] = useState([]);
  const [selectedCoupon, setSelectedCoupon] = useState();
  const [userInfo, setUserInfo] = useState({});
  const [orderDetailCache, setOrderDetailCache] = useState({});
  const [name, setName] = useState('');
  const [address, setAddress] = useState('');
  const {
    route: {
      params: {courseId},
    },
  } = props;
  useEffect(() => {
    //设置微信ID
    XPay.setWxId('wx3c636c9d085b9dac');
    // //设置    支付宝URL Schemes
    XPay.setAlipayScheme('alipay');
    const _fn = async () => {
      await courseDetail(courseId).then((res) => {
        console.log(res);
        setCourseData(res.data);
      });
      const profileResult = await profile();
      setUserInfo(profileResult?.data);
      console.log(profileResult);
      await couponcustList({
        custId: profileResult?.data?.custId,
        couponCustStatus: 1,
      }).then((res) => {
        console.log(res);
        const newCoupon = (res.rows || []).map((item) => ({
          ...item,
          label: item.couponName,
          value: item.couponCustId,
        }));
        setCouponData([...newCoupon]);
      });
    };
    _fn();
  }, [navigation]);
  const createOrderCommon = (callback) => {
    createOrder(
      !selectedCoupon
        ? {
            actualPrice: courseData?.coursePrice,
            totalPrice: courseData?.coursePrice,
            custId: userInfo?.custId,
            couponId: selectedCoupon,
            freePrice: 0,
            createBy: address || userInfo?.address,
            orderChannels: 2,
            orderStatus: 0,
            orderType: 1,
            isReceipt: 0,
            custName: name || userInfo?.custName,
            custAddress: address || userInfo?.address,
            receipt: {
              receiptKind: 1,
              headType: 1,
              receiptDesc: 1,
            },
            smOrderCmCourseList: [
              {
                cmCourseId: courseData?.courseId,
                cmCoursePrice: courseData?.coursePrice,
                cmCourseFreePrice: 0,
                cmCourseActualPrice: courseData?.coursePrice,
              },
            ],
          }
        : orderDetailCache,
    ).then((res) => callback(res));
  };
  const aliPayCLk = () => {
    createOrderCommon((res) => {
      if (res?.data?.orderStatus === '1') {
        navigation.push('MyOrder', {custId: userInfo?.custId});
        return;
      }
      console.log(res);
      if (res.code === 500) {
        Toast.info(res?.msg?.replace('null', ''), 2);
        return;
      }
      alipayAppPay({
        amt: res?.data?.actualPrice,
        billNo: res?.data?.orderNo,
        body: (res?.data?.smOrderCmCourseList || [])
          .map((item) => item.courseTitle)
          .join('/'),
        payType: '1',
        subject: '课程购买',
      }).then((orderRes) => {
        //支付宝支付
        XPay.alipay(orderRes.msg, (result) => {
          console.log(result, 'result');
          if (result.resultStatus === '9000') {
            navigation.push('MyOrder', {custId: userInfo?.custId});
          } else {
            Toast.fail('支付失败', 2);
          }
        });
      });
    });
  };
  const wechatPayCLk = () => {
    createOrderCommon((res) => {
      if (res?.data?.orderStatus === '1') {
        navigation.push('MyOrder', {custId: userInfo?.custId});
        return;
      }
      wxpayAppPay({
        amt: res?.data?.actualPrice,
        billNo: res?.data?.orderNo,
        body: (res?.data?.smOrderCmCourseList || [])
          .map((item) => item.courseTitle)
          .join('/'),
        payType: '1',
        subject: '课程购买',
      }).then((orderRes) => {
        console.log(orderRes);
        //微信支付
        //这些参数都是由后台生成的
        // let params = {
        //   partnerId: 'partnerId',
        //   prepayId: 'prepayId',
        //   packageValue: 'packageValue',
        //   nonceStr: 'nonceStr',
        //   timeStamp: 'timeStamp',
        //   sign: 'sign',
        // };
        // XPay.wxPay(
        //   params,
        //   (res) => console.log(res),
        //   (err) => {
        //     console.log(err);
        //   },
        // );
      });
    });
  };
  const payMoney = (couponId) => {
    orderCalculateAmt({
      actualPrice: courseData?.coursePrice,
      totalPrice: courseData?.coursePrice,
      createBy: address || userInfo?.address,
      custId: userInfo?.custId,
      couponId,
      orderChannels: 2,
      orderStatus: 0,
      orderType: 1,
      revision: 1,
      isReceipt: 0,
      custName: name || userInfo?.custName,
      custAddress: address || userInfo?.address,
      receipt: {
        receiptKind: 1,
        headType: 1,
        receiptDesc: 1,
      },
      smOrderCmCourseList: [
        {
          cmCourseId: courseData?.courseId,
          cmCoursePrice: courseData?.coursePrice,
          cmCourseFreePrice: 0,
          cmCourseActualPrice: courseData?.coursePrice,
        },
      ],
    }).then((res) => {
      console.log(res);
      setOrderDetailCache(res.data);
    });
  };
  const selectedCouponChange = (val) => {
    setSelectedCoupon(val);
    payMoney(val[0]);
  };
  return (
    <AreaView>
      <ScrollView style={styles.container}>
        <View style={styles.order_detail_container}>
          <Text style={styles.small_title}>
            欢迎购买此课程，请您支付提交订单并支付
          </Text>
          <View style={styles.order_detail}>
            <View style={styles.order_title}>
              <View style={styles.order_line} />
              <Text style={styles.order_title_text}>订单信息</Text>
            </View>
            <OrderPrdList courseData={courseData} />
            <List>
              <Picker
                data={couponData}
                cols={1}
                value={selectedCoupon}
                onChange={(val) => selectedCouponChange(val)}>
                <List.Item arrow="horizontal">
                  <Text style={styles.coupon_text}>优惠信息</Text>
                </List.Item>
              </Picker>
            </List>
            <View style={styles.order_prod_money}>
              <View style={styles.order_prod_money_top}>
                <Text style={styles.text1}>商品价格</Text>
                <Text style={styles.text2}>
                  ￥{courseData.freeCourse === 'Y' ? 0 : (orderDetailCache?.actualPrice || courseData?.coursePrice)}
                </Text>
              </View>
              <View style={styles.order_prod_money_bottom}>
                <Text style={styles.text3}>合计:</Text>
                <Text style={styles.text4}>
                  ￥{courseData.freeCourse === 'Y' ? 0 : (orderDetailCache?.actualPrice || courseData?.coursePrice)}
                </Text>
              </View>
            </View>
            <View style={styles.gap} />
            <View style={styles.order_title}>
              <View style={styles.order_line} />
              <Text style={styles.order_title_text}>用户信息</Text>
            </View>
            <View style={styles.content}>
              <View style={styles.content_info}>
                <View style={styles.info_list}>
                  <Text style={styles.label}>用户名:</Text>
                  <Text style={styles.label_text}>{userInfo?.userName}</Text>
                </View>
                <View style={styles.info_list}>
                  <Text style={styles.label}>姓 名:</Text>
                  <TextInput
                    placeholder="请输入姓名"
                    style={(styles.label_input, {padding: 0})}
                    defaultValue={userInfo?.custName}
                    onChangeText={(val) => {
                      setName(val);
                    }}
                  />
                </View>
                <View style={styles.info_list}>
                  <Text style={styles.label}>手机号:</Text>
                  <Text style={styles.label_text}>{userInfo?.phone}</Text>
                </View>
                <View style={styles.info_list}>
                  <Text style={styles.label}>地 址:</Text>
                  <TextInput
                    style={(styles.label_input, {padding: 0})}
                    placeholder="请输入地址"
                    defaultValue={userInfo?.address}
                    onChangeText={(val) => {
                      setAddress(val);
                    }}
                  />
                </View>
                <Text style={styles.order_invoic_text}>
                  说明：地址用于纸质发票邮寄，如需要请填写
                </Text>
              </View>
            </View>
            <View style={styles.gap} />
            <View style={styles.order_title}>
              <View style={styles.order_line} />
              <Text style={styles.order_title_text}>请选择支付方式</Text>
            </View>
            <View style={styles.pay_type}>
              <View style={styles.pay_type_btn}>
                <TouchableOpacity  activeOpacity={1} activeOpacity={1}>
                  <Image
                    style={styles.pay_img_icon}
                    source={require('../../assets/images/alipay.png')}
                  />
                </TouchableOpacity>
                {/* <TouchableOpacity  activeOpacity={1} onPress={wechatPayCLk}>
                  <Image
                    style={styles.pay_img_icon}
                    source={require('../../assets/images/wechat.png')}
                  />
                </TouchableOpacity> */}
              </View>
              <Text style={styles.pay_info_text}>
                请您在60分钟内完成支付，预期订单将失效
              </Text>
            </View>
            <View style={styles.order_sure_btn_container}>
              <TouchableOpacity
                style={styles.order_sure_btn}
                onPress={aliPayCLk}>
                <Text style={styles.order_sure_btn_text}>确认支付</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </ScrollView>
    </AreaView>
  );
};

export default PaySure;
